<?php

function EJGetDiet(&$parameters) {
    $aid = "aidDiet";
    return EJExecuteWithAuthenticatedFamily($aid, $parameters, function ($fid, $aid, &$parameters) {
        $paramOffset = 1; # The first one is the whole string from reg match
        $person = $parameters[W3GetAPIParamIndex($aid, "person") + $paramOffset];
        $date = $parameters[W3GetAPIParamIndex($aid, "datetime") + $paramOffset];

        $sql = "select " .
             "diet.Diet as diet" .
             " from " .
             "diet, person" .
             " where " .
             "diet.Datetime = '" . strval($date) . "'" .
             " and " .
             "diet.Person = person.ID" .
             " and " .
             "person.ID = " . $person .
             " and " .
             "person.FID = " . $fid;
        $result = "{" . W3CreateSuccessfulPartialResult() . "," . W3MakeString(w3ApiResultData) . ":[";
        EJReadTable($sql, function ($row) use (&$result, $aid) {
            $apiDef = W3GetAPIDef($aid);
            $columns = $apiDef[w3ApiResult][w3ApiResultData];
            $result .= "{";
            foreach ($columns as $value) {
                $resultForColumn = $row[$value[w3ApiDataValue]];
                $result .= W3MakeString($value[w3ApiDataValue]) . ":" . W3MakeString($resultForColumn) . ",";
            }
            $result = rtrim($result, ",") . "},";
        });
        $result = rtrim($result, ",") . "]}";

        return $result;
    });
}

function EJUpdateDiet(&$parameters) {
    $aid = "aidUpdateDiet";
    return EJExecuteWithAuthenticatedFamily($aid, $parameters, function ($fid, $aid, &$parameters) {
        $paramOffset = 1; # The first one is the whole string from reg match
        $person = $parameters[W3GetAPIParamIndex($aid, "person") + $paramOffset];
        if (!EJIsPersonInFamily($person, $fid)) {
            W3LogWarning("Try to update diet not belong to family!");
            return W3CreateFailedResult();
        }

        if (EJInsertDiet($parameters)) {
            return W3CreateSuccessfulResult();
        }

        return W3CreateFailedResult();
    });
}

function EJCreateLivingMenu($pid = null) {
    // Read menu from note "Food" in family
    $session = W3GetSession();
    $fid = EJGetLoginFamily($session);
    if ($fid == null) {
        W3LogWarning("Failed to get family ID to create living menu");
        return "<p>Login first please!</p>";
    }
    $menu = "";
    $sql = "select Note from note where Title='Food' and FID=" . $fid;
    EJReadTable($sql, function ($row) use (&$menu) {
        $menu = W3Decode($row["Note"]);
    });

    // Get menu titles
    $h1Pattern = "/<h1>(.*)<\/h1>/U";
    preg_match_all($h1Pattern, $menu, $h1Array);
    if (sizeof($h1Array) == 0) {
        return "";
    }
    $titleMap = array(1 => array(),
                      2 => array(),
                      3 => array(),
                      4 => array(),
                      5 => array());
    $menuCount = 0;
    $maxStar = 5;
    foreach ($h1Array[1] as $titleMatch) {
        $title = preg_replace("/\*+/", "", $titleMatch);
        $star = strlen($titleMatch) - strlen($title);
        if ($star < 1) {
            $star = 1;
        }
        if ($star > $maxStar) {
            $star = $maxStar;
        }
        array_push($titleMap[$star], array($menuCount++, $title));
    }

    // Get contents
    $h3Pattern = "/<h3>(.*)<\/h3>/U";
    $ulPattern = "/<ul>(.*)<\/ul>/U";
    preg_match_all($h3Pattern, $menu, $h3Array);
    preg_match_all($ulPattern, $menu, $ulArray);
    if ((sizeof($h3Array) == 0) || (sizeof($ulArray) == 0)) {
        W3LogWarning("No menu contents!");
        return "";
    }
    if (sizeof($h3Array[0]) != sizeof($ulArray[0])) {
        W3LogWarning("Menu operation and stuff are not match!");
        return "";
    }
    $index = 1;
    $menuContents = array();
    while ($index < sizeof($h3Array[0])) {
        if (($index + 1 == sizeof($h3Array[0])) ||
            (strlen($h3Array[0][$index]) == strlen($h3Array[0][$index + 1]))) {
            // There is only $index - 1: "stuff" and $index: "operation"
            // Because "tips" is longer
            array_push($menuContents, array($ulArray[0][$index - 1], $ulArray[0][$index], ""));
            $index += 2;
        } else {
            // The $index + 1 is "tips"
            array_push($menuContents, array($ulArray[0][$index - 1], $ulArray[0][$index], $ulArray[0][$index + 1]));
            $index += 3;
        }
    }
    if (sizeof($menuContents) != $menuCount) {
        W3LogWarning("Menu tilte and contents are not match!");
        return "";
    }

    // Create Title UI
    $menuUI = "<div><table><tbody>";
    $menuUI .= "<tr>";
    for ($i = 0; $i < $maxStar; ++$i) {
        $startStr = "";
        for ($j = $i; $j < $maxStar; ++$j) {
            $startStr .= "*";
        }
        $menuUI .= "<th>" . $startStr . "</th>";
    }
    $menuUI .= "</tr>";
    for ($iRow = 0; $iRow < $menuCount; ++$iRow) {
        $thereIsMenu = false;
        $menuUI .= "<tr>";
        for ($iColumn = 0; $iColumn < $maxStar; ++$iColumn) {
            $starMap = $titleMap[$maxStar - $iColumn];
            if ($iRow < sizeof($starMap)) {
                $thereIsMenu = true;
                $ijID = $starMap[$iRow][0];
                $ijTitle = $starMap[$iRow][1];
                $menuUI .= "<td><button onclick='EJMenuDisplay(" . $ijID . "," . $menuCount . ")' type='button'>" . $ijTitle . "</button></td>";
            } else {
                $menuUI .= "<td></td>";
            }
        }
        $menuUI .= "</tr>";
        if (!$thereIsMenu) {
            break;
        }
    }
    $menuUI .= "</tbody></table></div>";

    // Create Menu UI
    $menuUIStuff = "<div><hr/></div><div>";
    $menuUIOperation = "<div><hr/></div><div>";
    $menuUITips = "<div><hr/></div><div>";
    for ($iMenu = 0; $iMenu < $menuCount; ++$iMenu) {
        $menuUIStuff .= "<div id='uidMenuStuff" . $iMenu . "' style='display:none'>" . $menuContents[$iMenu][0] . "</div>";
        $menuUIOperation .= "<div id='uidMenuOperation" . $iMenu . "' style='display:none'>" . $menuContents[$iMenu][1] . "</div>";
        $menuUITips .= "<div id='uidMenuTips" . $iMenu . "' style='display:none'>" . $menuContents[$iMenu][2] . "</div>";
    }
    $menuUIStuff .= "</div>";
    $menuUIOperation .= "</div>";
    $menuUITips .= "</div>";
    $menuUI .= "<div>" . $menuUIStuff . $menuUIOperation . $menuUITips . "</div>";

    return $menuUI;
}

function EJInsertDiet(&$dietParams) {
    if (!EJConnectDB()) {
        W3LogWarning("No DB connection when insert debt");
        return false;
    }

    $columns = array ("Person", "Datetime", "Diet", "Session");
    $size = sizeof($columns);

    $uselessParamCount = 1; # Match string, session, etc.
    $paramOffset = 1; # 0 is for the whole match string in reg
    if (sizeof($dietParams) - $uselessParamCount != $size) {
        W3LogWarning("No enough fields for diet insert: require " .
                   strval($size) .
                   " but actual is " .
                   strval(sizeof($dietParams) - $paramOffset));
        return false;
    }

    $aid = "aidUpdateDiet";
    $dietPerson = $dietParams[W3GetAPIParamIndex($aid, "person") + $paramOffset];
    $dietDatetime = W3MakeSingleQuotString($dietParams[W3GetAPIParamIndex($aid, "datetime") + $paramOffset]);
    $dietValue = $dietParams[W3GetAPIParamIndex($aid, "diet") + $paramOffset];

    $values = array($dietPerson, $dietDatetime, $dietValue);

    $sql = "insert into diet values (" . implode (",", $values) . ")";
    if (EJExecuteSQL($sql)) {
        return true;
    }

    $sql = "update diet set Diet=" . strval($dietValue) .
         " where Person=" . strval($dietPerson) . " and Datetime=" . $dietDatetime;

    if (!EJExecuteSQL($sql)) {
        W3LogWarning("Execute Diet insert SQL failed");
        return false;
    }

    return true;
}

 ?>
